﻿#ifndef GL_WIDGET_H_
#define GL_WIDGET_H_

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QImage>
#include <QDialog>
#include <QLineEdit>
#include <QDialogButtonBox>
#include "JZGLCamera.h"
#include "JZGLScene.h"
#include "JZGLItem.h"

class JZGLCameraConfigDialog : public QDialog
{
    Q_OBJECT

public:
    JZGLCameraConfigDialog(QWidget *parent);

    void setCamera(JZGLCamera *camera);

protected slots:
    void onBtn(QAbstractButton *button);

protected:    
    virtual void accept() override;
    void apply();

    QDialogButtonBox *m_btnBox;
    JZGLCamera *m_camera;
    QList<QLineEdit*> m_lineList;
};

class JZGLView : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    JZGLView(QWidget* parent = nullptr);
    ~JZGLView();

    JZGLCamera* camera();

    void setScene(JZGLScene* scene);
    JZGLScene* scene();

    void setViewport(int x,int y,int w,int h);
    void updateItemBuffer();

    QPoint worldToPixel(QVector3D world);
    QVector3D pixelToWorld(QPoint pt);
    float getDepth(int x, int y);

protected slots:
    void onContextMenu(QPoint pt);

protected:
    void initializeGL() override;
    void resizeGL(int w, int h) override;
    void paintGL() override;

private:

    virtual void mousePressEvent(QMouseEvent* e) override;
    virtual void mouseMoveEvent(QMouseEvent* e) override;
    virtual void mouseReleaseEvent(QMouseEvent* e) override;

    virtual void keyPressEvent(QKeyEvent* event) override;
    virtual void keyReleaseEvent(QKeyEvent* event) override;

    void initShaders();    
    void draw3DItems();
    void draw2DItems();

    QVector<float> vertexToFloat(const QVector<VertexData>& points);

    QOpenGLShaderProgram m_program;
    JZGLCamera m_camera;
    JZGLScene* m_scene;

    QOpenGLBuffer m_vertexBuffer;
    QOpenGLBuffer m_meshIndexBuffer;    
    QOpenGLBuffer m_lineIndexBuffer;
    QOpenGLBuffer m_pointIndexBuffer;
    QMatrix4x4 m_worldModel;

    double m_highDpi;
    QPoint m_mouseDownPos;
    bool m_mouseDown;
};

#endif // !GL_WIDGET_H_